<?php
namespace app\common;
use app\common\logic\AuthManager;
/**
 * API权限验证
 * Class AuthApi
 * @package app\common
 */
class AuthApi extends Base {
	protected $AuthKey='';//权限令牌
	protected $SessionId='';//session id
	protected $AuthType='';//权限类别
	protected $AuthData='';//认证数据
	protected $CheckRight=true; //是否检测权限
	protected $IgnoreAction=['login','logout'];//需要忽略权限检测的方法

	public function _initialize(){
		//获取头部信息
		$header = $this->request->header();
		$this->AuthKey = isset($header['authkey'])?$header['authkey']:'';
		$cache = cache('Auth_'.$this->AuthKey);
		//部分action可以忽略access_token权限检查
		if(!in_array($this->request->action(),$this->IgnoreAction)){
			// 校验权限
			if (empty($this->AuthKey)||empty($cache)) {
				abort(json(['state'=>100,'mess'=>'登录失效','data'=>strtolower($this->AuthType)]));
			}
			//检验auth_key数据是否有误
			if(false===$this->checkAuthKey()){
				abort(json(['state'=>100,'mess'=>'登录失效','data'=>strtolower($this->AuthType)]));
			}
			//检验是否需要续期
			AuthManager::updateKey($this->AuthKey);
		}
	}

	//需要重写
	protected function checkAuthKey(){
		if(!$this->AuthKey) return false;
		$this->AuthData=AuthManager::getData($this->AuthKey);
		if(false==$this->AuthData){
			return false;
		}
		//检测type类型是否一样
		if(!$this->AuthData ||strtolower($this->AuthData['auth_type'])!=strtolower($this->AuthType)) return false;
		else return true;
	}



}